import { ApiGetCourseDetail, KeyApiGetCourseDetail, type ExperimentModel } from '@/apis/course'
import { useQuery } from '@tanstack/vue-query'
import { computed, type Ref } from 'vue'

export function useCourse(courseID: Ref<number>) {
  const { data, isLoading } = useQuery({
    enabled: computed(() => courseID.value !== 0),
    queryKey: computed(() => KeyApiGetCourseDetail(courseID.value)) as Ref<
      ReturnType<typeof KeyApiGetCourseDetail>
    >,
    staleTime: 60_000,
    queryFn: ({ queryKey: [, , id] }) => ApiGetCourseDetail(id),
    select({ data: { experimentMeta, experiments, ...course } }) {
      const metaMap = new Map(experimentMeta.map(({ id, ...meta }) => [id, meta]))

      return {
        course,
        experiments: experiments
          .sort((a, b) => metaMap.get(a.id)!.index - metaMap.get(b.id)!.index)
          .map<ExperimentModel & { meta: string }>((base) => ({
            ...base,
            meta: metaMap.get(base.id)!.meta
          }))
      }
    }
  })

  return {
    course: data,
    isLoading
  }
}
